package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;

import dao.PhotoDao;
import entity.Photo;

public class PhotoDaoJdbcImpl implements PhotoDao {

	@Override
	public void save(Photo photo) throws Exception {
		String name=photo.getName();
		int userId=photo.getUserId();
		
		String sql="insert into friend_pic (name,userid) values(?,?)";
		Connection con=null;
		PreparedStatement pst=null;
		try {
			con=DBUtil.openInThread();
			pst=con.prepareStatement(sql);
			pst.setString(1, name);
			pst.setInt(2, userId);
			pst.execute();
		} finally {
			DBUtil.close(null, pst, null);
			DBUtil.closeInThread();
		}
	}

	@Override
	public List<Photo> findByUserId(int userId) throws Exception {
		List<Photo> photos=new ArrayList<Photo>();
		String sql="select * from friend_pic where userid=?";
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs = null;
		try {
			con=DBUtil.openInThread();
			pst=con.prepareStatement(sql);
			pst.setInt(1, userId);
			rs=pst.executeQuery();
			while(rs.next()){
				Photo photo = new Photo();
				photo.setName(rs.getString("name"));
				photos.add(photo);
			}
			return photos;
		} finally {
			DBUtil.close(null, pst, rs);
			DBUtil.closeInThread();
		}
	}

}
